package simple.persistence.dao;

import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import simple.persistence.entity.User;

import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.persistence.*;
import javax.transaction.UserTransaction;

import java.util.List;

@Stateless
public class UserDAO implements UserDAOInterface {
    private static Log log = LogFactory.getLog(UserDAO.class);

    @PersistenceUnit(unitName = "SimpleEntityManager")
    EntityManagerFactory emf;

    @PersistenceContext(unitName = "SimpleEntityManager")
    private EntityManager em;

    private EntityManager getEntityManager() {
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("SimpleEntityManager");
        }
        if (em == null) {
            em = emf.createEntityManager();
        }
        return em;
    }

    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
        log.debug("getUsers");
        List<User> users = Lists.newArrayList();
        users.addAll(getEntityManager().createQuery("select user from User user order by user.lastName").getResultList());
        return users;
    }

    public User saveUser(User user) {
        try {
            log.debug("saveUser: " + user);
            getEntityManager().persist(user);

            UserTransaction transaction = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
            transaction.begin();
            getEntityManager().joinTransaction();
            transaction.commit();
        } catch (Exception e) {
            log.error("Exception: " + e.getMessage());
        }
        return user;
    }

    @SuppressWarnings("unchecked")
    public List<User> findUsersBySearchTerm(String term) {
        List<User> users = Lists.newArrayList();
        users.addAll(getEntityManager().createQuery("select user from User user where user.firstName like :term or user.lastName like :term order by user.lastName").setParameter("term", term).getResultList());
        return users;
    }

    public void setEm(EntityManager em) {
	    this.em = em;
    }
    
}
